//
//  JAKeyboardToolbar.swift
//  JAWeiBo
//
//  Created by Arvin on 17/4/13.
//  Copyright © 2017年 Arvin. All rights reserved.
//

import UIKit

fileprivate let baseTag = 88

protocol JAKeyboardToolbarDelegate: NSObjectProtocol {
    func toggleKeyboard(section: Int)
}

class JAKeyboardToolbar: UIStackView {
    weak var delegate: JAKeyboardToolbarDelegate?
    
    //记录选中的button
    var selectedButton: UIButton?
    
    var selectedIndex: Int = 0 {
        didSet {
            let selectedTag = selectedIndex + baseTag
            let button = viewWithTag(selectedTag) as! UIButton
            selectedButton?.isSelected = false
            button.isSelected = true
            selectedButton = button
        }
    }
    
   override init(frame: CGRect) {
        super.init(frame: frame)
    
        //水平还是垂直分布
        axis = .horizontal
    
        //等距平均分布
        distribution = .fillEqually
    
         setupUI()
    }
    
    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension JAKeyboardToolbar {
    func setupUI () {
        let buttonDicArr: [[String: Any]] = [["title": "最近", "image": "left"],
                                             ["title": "默认", "image": "mid"],
                                             ["title": "emoji", "image": "mid"],
                                             ["title": "浪小花", "image": "right"]]
        for (index, dic) in buttonDicArr.enumerated() {
            let title = dic["title"] as! String
            let imageName = dic["image"] as! String
            let normalImageName = "compose_emotion_table_\(imageName)_normal"
            let selectedImage = UIImage(named: "compose_emotion_table_\(imageName)_selected")
            
            let button = UIButton(title: title, titleColor: UIColor.white, fontSize: 16,  bgImage: normalImageName, target: self, action: #selector(toggleKeyobard(button:)))
            
            //设置button的选中状态的文字和背景图片
            button.setTitleColor(UIColor.darkGray, for: .selected)
            button.setBackgroundImage(selectedImage, for: .selected)
            
            button.tag = index + baseTag
            
            //和addSubView的效果是一样的
            addArrangedSubview(button)
            
            if index == 0 {
                button.isSelected = true
                selectedButton = button
            }
            
        }
    }
}

extension JAKeyboardToolbar {
    @objc fileprivate func toggleKeyobard(button: UIButton) {
        
        selectedButton?.isSelected = false
        button.isSelected = true
        selectedButton = button
        
        delegate?.toggleKeyboard(section: button.tag - baseTag)
    }
}
